//
//  MoveDemo.hpp
//  learnC++
//
//  Created by liuzhibing on 2018/6/28.
//  Copyright © 2018年 yunfan.com. All rights reserved.
//

#ifndef MoveDemo_hpp
#define MoveDemo_hpp

#include <stdio.h>
#include <iostream>
#include <chrono>

template <class T>
class DynamicArray {
private:
    T *m_array;
    int m_length;
    
public:
    DynamicArray(int length):m_array(new T[length]),m_length(length){
    }
    ~DynamicArray(){
        delete []m_array;
    }
    /*
     复制构造函数和赋值
    DynamicArray(const DynamicArray &arr):m_length(arr.m_length){
        m_array = new T[m_length];
        for (int i = 0; i < m_length; ++i) {
            m_array[i] = arr.m_array[i];
        }
        
    }
    
    DynamicArray &operator=(const DynamicArray &arr){
        if (&arr == this) {
            return *this;
        }
        
        delete [] m_array;
        
        m_length = arr.m_length;
        m_array = new T[m_length];
        
        for (int i = 0; i < m_length; ++i)
            m_array[i] = arr.m_array[i];
        
        return *this;
    }*/
    
    
    DynamicArray(const DynamicArray & arr) = delete;
    
    DynamicArray &operator=(const DynamicArray &arr) = delete;
    //移动构造函数和移动语义(注意参数2个&&)
    DynamicArray(DynamicArray &&arr):m_length(arr.m_length),m_array(arr.m_array){
        arr.m_array = nullptr;
        arr.m_length = 0;
    }
    
    DynamicArray &operator=(DynamicArray &&arr){
        
        if (&arr == this) {
            return *this;
        }
        
        delete [] m_array;
        
        m_length = arr.m_length;
        m_array = arr.m_array;
        
        arr.m_array = nullptr;
        arr.m_length = 0;
        return *this;
    }
    
    int getLength() const {return m_length;}
    T &operator[](int index){
        return m_array[index];
    }
    const T &operator[](int index) const{
        return m_array[index];
    }
    
};

class Timer {
private:
    using clock_t = std::chrono::high_resolution_clock;
    using second_t = std::chrono::duration<double,std::ratio<1>>;
    
    std::chrono::time_point<clock_t> m_beg;
    
public:
    Timer():m_beg(clock_t::now()){
        
    }
    void reset()
    {
        m_beg = clock_t::now();
    }
    
    double elapsed() const
    {
        return std::chrono::duration_cast<second_t>(clock_t::now() - m_beg).count();
    }
    
};

DynamicArray<int> cloneArrayAndDouble(const DynamicArray<int> &arr);

/*
 Timer t;
 DynamicArray<int> arr(100000);
 
 for (int i = 0; i < arr.getLength(); i++)
 arr[i] = i;
 
 arr = cloneArrayAndDouble(arr);
 std::cout << t.elapsed();
 */


#endif /* MoveDemo_hpp */
